package com.systop.ltbook.sms.webapp;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.hibernate.criterion.MatchMode;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;

import com.systop.cms.utils.PageUtil;
import com.systop.common.modules.security.user.LoginUserService;
import com.systop.common.modules.security.user.model.User;
import com.systop.core.dao.support.Page;
import com.systop.core.webapp.struts2.action.ExtJsCrudAction;
import com.systop.ltbook.sms.SmsConstants;
import com.systop.ltbook.sms.model.SmsSend;
import com.systop.ltbook.sms.service.SmsSendManager;

/**
 * 短息管理的struts2 Action。
 * 
 * @author DU
 * 
 */
@SuppressWarnings( { "serial", "unchecked" })
@Controller
@Scope(BeanDefinition.SCOPE_PROTOTYPE)
public class SmsSendAction extends ExtJsCrudAction<SmsSend, SmsSendManager> {

	@Autowired
	private LoginUserService loginUserService;
	
	/** 短信ID */
	private String smsSendId;
	
	/** 短信详细信息 */
	private Map smsSendInfo;
	
	/** 接收人ID序列 */
	private String receiverIds;
	
	/** 短信发送开始时间 */
	private Date startDate;
	
	/** 短信发送结束时间 */
	private Date endDate;
	
	/** 剩余发送条数 */
	private Integer remainSize = 0;
	
	/**
	 * 短信发送列表
	 */
	@Override
	public String index() {
		Page page = PageUtil.getPage(getPageNo(), getPageSize());
		StringBuffer hql = new StringBuffer("from SmsSend s where 1=1");
		List args = new ArrayList();
		User sender = loginUserService.getLoginUser(getRequest());
		//当前系统登陆人员所发的短信
		if (sender != null) {
			hql.append(" and s.sender.id = ?");
			args.add(sender.getId());
		}
		if (StringUtils.isNotBlank(getModel().getReceiverName())) {
			hql.append(" and s.receiverName like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getReceiverName()));
		}
		if (StringUtils.isNotBlank(getModel().getMobileNum())) {
			hql.append(" and s.mobileNum like ?");
			args.add(MatchMode.ANYWHERE.toMatchString(getModel().getMobileNum()));
		}
		if (StringUtils.isNotBlank(getModel().getIsNew())) {
			hql.append(" and s.isNew = ?");
			args.add(getModel().getIsNew());
		}
		//按短信发送时间
    if (startDate != null && endDate != null) {
      hql.append(" and s.sendTime >= ? and s.sendTime <= ? ");
      args.add(startDate);
      args.add(endDate);
    }
		hql.append(" order by s.isNew desc,s.createTime desc");
		page = getManager().pageQuery(page, hql.toString(), args.toArray());
		restorePageData(page);
		
		return INDEX;
	}
	
	/**
	 * 短信发送
	 */
	public String save(){
		User user = loginUserService.getLoginUser(getRequest());
		String mobiles = getRequest().getParameter("mobiles");
		String content = getRequest().getParameter("content");
		String smsNums = getRequest().getParameter("smsNums");
		//logger.debug("分：" + smsNums + " 条发送");
		Integer nums = 1;
		if (StringUtils.isNotBlank(smsNums)) {
			nums = Integer.valueOf(smsNums);
		}
		String[] mobNums = new String[]{};
		if (StringUtils.isNotEmpty(mobiles)) {
			mobNums = mobiles.split(";");
			for (String num : mobNums){
				SmsSend smsSend = new SmsSend();
				//新短信
				smsSend.setIsNew(SmsConstants.SMS_SEND_IS_NEW);
				smsSend.setMobileNum(num);
				smsSend.setContent(content);
				smsSend.setSmsNums(nums);
				smsSend.setCreateTime(new Date());
				//发送人为系统登陆人员
				if (user != null) {
					smsSend.setSender(user);
				}
				getManager().save(smsSend);
			}
		}
		StringBuffer hasNoNum = new StringBuffer("");
		String[] uIds = new String[]{};
		if (StringUtils.isNotEmpty(receiverIds)) {
			uIds = receiverIds.split(",");
			for(String id : uIds){
				if (StringUtils.isNumeric(id)){
					User u = getManager().getDao().get(User.class, Integer.valueOf(id));
					if (u != null){
						if (StringUtils.isNotBlank(u.getMobile())) {
							SmsSend smsSend = new SmsSend();
							//新短信
							smsSend.setIsNew(SmsConstants.SMS_SEND_IS_NEW);
							smsSend.setMobileNum(u.getMobile());
							smsSend.setContent(content);
							smsSend.setSmsNums(nums);
							smsSend.setCreateTime(new Date());
							//接收人姓名
							smsSend.setReceiverName(u.getName());
							//发送人为系统登陆人员
							if (user != null) {
								smsSend.setSender(user);
							}
							getManager().save(smsSend);
						} else {
							hasNoNum.append(u.getName()).append(" ");
						}
					} 
				}
			}
		}
		
		if (StringUtils.isNotBlank(hasNoNum.toString())) {
			addActionError("接收人：" + "<font color='red'>" + hasNoNum.toString() + "</font>" + "没有手机号码！");
			return INPUT;
		}
		
		return SUCCESS;
	}
	
	/**
	 * 发送短信编辑
	 */
	@Override
	public String edit() {
		User user = loginUserService.getLoginUser(getRequest());
		if (user != null) {
			remainSize = getManager().getSmsSendRemainSize(user);
		}
		
		return super.edit();
	}
	
	/**
	 * 查看发送的短信内容
	 */
	public String viewSmsSendInfo() {
		if (StringUtils.isNotBlank(smsSendId)) {
			smsSendInfo = getManager().getSmsMapById(smsSendId);;
		}
  	return "jsonRst";
	}

	public String getSmsSendId() {
  	return smsSendId;
  }

	public void setSmsSendId(String smsSendId) {
  	this.smsSendId = smsSendId;
  }

	public Map getSmsSendInfo() {
  	return smsSendInfo;
  }

	public void setSmsSendInfo(Map smsSendInfo) {
  	this.smsSendInfo = smsSendInfo;
  }

	public String getReceiverIds() {
  	return receiverIds;
  }

	public void setReceiverIds(String receiverIds) {
  	this.receiverIds = receiverIds;
  }

	public Date getStartDate() {
  	return startDate;
  }

	public void setStartDate(Date startDate) {
  	this.startDate = startDate;
  }

	public Date getEndDate() {
  	return endDate;
  }

	public void setEndDate(Date endDate) {
  	this.endDate = endDate;
  }

	public Integer getRemainSize() {
  	return remainSize;
  }

	public void setRemainSize(Integer remainSize) {
  	this.remainSize = remainSize;
  }
}
